package org.gosilver.beans.factory.support.instantiate;

import org.gosilver.beans.BeansException;
import org.gosilver.beans.factory.config.BeanDefinition;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * JDK 反射 实例化
 */
public class SimpleInstantiationStrategy implements InstantiationStrategy {
    @Override
    public Object instantiate(BeanDefinition beanDefinition,
                              String beanName,
                              Constructor ctor,
                              Object[] args) throws BeansException {
        Class clazz = beanDefinition.getBeanClass().getClass();
        try {
            // 判断 ctor 是否为空，如果为空则是无构造函数实例化，否则就是需要有构造函数的实例化
            if (ctor != null) {
                return clazz.getDeclaredConstructor(ctor.getParameterTypes()).newInstance(args);
            } else {
                return clazz.getDeclaredConstructor().newInstance();
            }
        } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
            throw new BeansException("Failed to instantiate [" + clazz.getName() + "]", e);
        }
    }

}
